package com.px.system.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.px.biz.domain.*;
import com.px.biz.dto.RukuExcelDTO;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.px.system.domain.ChanpingDO;
import com.px.system.domain.CkkucunDO;
import com.px.system.domain.RukuDO;
import com.px.system.service.ChanpingService;
import com.px.system.service.CkkucunService;
import com.px.system.service.RukuService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.px.biz.service.IPurchaseContractService;
import com.px.biz.service.IPurchaseOrderDetailService;
import com.px.biz.service.IPurchaseOrderService;
import com.px.common.annotation.Log;
import com.px.common.utils.PageUtils;
import com.px.common.utils.Query;
import com.px.common.utils.R;
import com.px.common.utils.ShiroUtils;
import com.px.common.utils.StringUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 
 * @author 品讯科技
 * @email zly@hnpinxun.cn
 * @date 2024-08
 */
 
@Controller
@RequestMapping("/system/ruku")
public class RukuController {
	@Autowired
	private CkkucunService ckkucunService;
	@Autowired
	private RukuService rukuService;
	  @Autowired
	    private IPurchaseOrderService purchaseOrderService;
	    @Autowired
	    private IPurchaseContractService purchaseContractService;
	    @Autowired
	    private IPurchaseOrderDetailService purchaseOrderDetailService;
	    @Autowired
	    private ChanpingService chanpingService;
	@GetMapping()
	@RequiresPermissions("system:ruku:ruku")
	String Ruku(){
	    return "system/ruku/ruku";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("system:ruku:ruku")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<RukuDO> rukuList = rukuService.list(query);
		int total = rukuService.count(query);
		PageUtils pageUtils = new PageUtils(rukuList, total);
		return pageUtils;
	}
	
	@ResponseBody
	@GetMapping("/cgList")
	@RequiresPermissions("system:ruku:ruku")
	public PageUtils cgList(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<RukuDO> rukuList = rukuService.cgList(query);
		int total = rukuService.cgCount(query);
		PageUtils pageUtils = new PageUtils(rukuList, total);
		return pageUtils;
	}
	
	
	@Log("每月举报次数")
	    @GetMapping("/jubaio2")
	    @ResponseBody
	    public List<Map<String, Object>> jubao(String date)throws UnsupportedEncodingException {
		 JSONObject result = null;
		 
		/* HashMap<String, Object> paramMap = new HashMap<>();
		 paramMap.put("token", "b0bb4cdb1fa845bb823e4991083ba1f2/zxdWXy/bXo=");
		 paramMap.put("areacode", "3209");
		 paramMap.put("igasvid", "IGASV3209C27");
		 paramMap.put("days", "0");*/
			String json = "{\"token\":\"b0bb4cdb1fa845bb823e4991083ba1f2/zxdWXy/bXo=\",\"areacode\":\"3209\",\"igasvid\":\"IGASV3209C27\",\"days\":\"1\"}";
		 String response= HttpUtil.post("https://ex.igasv.com/use_czjc", json);
		 String quStr=response.substring(response.indexOf("[")+1,response.indexOf("]"));
	       String name="["+quStr+"]";
	        System.out.println(quStr);
		/* ArrayList<HashMap> orderDetails = new ArrayList<>();*/
		 List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
		 
		 List<Object> list =JSON.parseArray(name);
		 
		 for (Object object : list){
		        Map<String,Object> ageMap = new HashMap<String,Object>();
		        Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
		      /* for (Entry<String, Object> entry : ret.entrySet()) { 
		            ageMap.put(entry.getKey());
		            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
		            listw.add(ageMap);  //添加到list集合  成为 list<map<String,Object>> 集合
		        }  */
		        listw.add(ret);
		        }
		  
		 for(int i = 0 ; i < listw.size() ; i ++){
			 	//
			    listw.get(i).get("name_cz");    //循环打印list里面map键为"A"的值,类型为Object
			    //车牌号
			    listw.get(i).get("cphm");    // 打印"A"的值,Object转成String
			    //汽车进来时间
			  listw.get(i).get("czqjcrq");    //打印"A"的值,Object转成String,String转成Integer
			}
		 
		 
		 
		  System.out.println(listw);
		 
	        return listw;
	    }
	

		
	
	@GetMapping("/add")
	@RequiresPermissions("system:ruku:add")
	String add(){
	    return "system/ruku/add";
	}

	@RequestMapping("detail")
    @ResponseBody
    public R detail(@RequestParam("cgId") String cgId,Model model){
		  PurchaseOrderDO purchaseOrder = purchaseOrderService.getById(cgId);
	        Map<String, Object> map = BeanUtil.beanToMap(purchaseOrder);
	        String contractId = purchaseOrder.getContractId();
	        if (StringUtils.isNotEmpty(contractId)) {
	            PurchaseContractDO byId = purchaseContractService.getById(contractId);
	            if (byId == null) {
	                map.remove("contractId");
	            } else {
	                map.put("contractCode", byId.getCode());
	            }
	        }
	        List<PurchaseOrderDetailDO> details = purchaseOrderDetailService.list(
	                new LambdaQueryWrapper<PurchaseOrderDetailDO>()
	                        .eq(PurchaseOrderDetailDO::getOrderId, cgId)
	        );
	        ArrayList<HashMap> orderDetails = new ArrayList<>();
	        for (PurchaseOrderDetailDO detail : details) {
	            HashMap<String, Object> orderDetail = new HashMap<>();
	            ChanpingDO chanpingDO = chanpingService.get(detail.getProductId());
	            orderDetail.put("productId", detail.getProductId());
	            orderDetail.put("price", detail.getPrice());
	            orderDetail.put("num", detail.getNum());
	            orderDetail.put("productName", chanpingDO.getCpName());
	            orderDetail.put("detailId", detail.getId());
	            orderDetails.add(orderDetail);
	        }
	        model.addAttribute("purchaseOrder", map);
	        model.addAttribute("orderDetails", orderDetails);
	        return R.ok().put("orderDetails", orderDetails);
	    
    }
	
	@GetMapping("/edit/{id}")
	@RequiresPermissions("system:ruku:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		
		RukuDO ruku = rukuService.get(id);
		
		
		  PurchaseOrderDO purchaseOrder = purchaseOrderService.getById(ruku.getCgId());
	        Map<String, Object> map = BeanUtil.beanToMap(purchaseOrder);
	        String contractId = purchaseOrder.getContractId();
	        if (StringUtils.isNotEmpty(contractId)) {
	            PurchaseContractDO byId = purchaseContractService.getById(contractId);
	            if (byId == null) {
	                map.remove("contractId");
	            } else {
	                map.put("contractCode", byId.getCode());
	            }
	        }
	        List<PurchaseOrderDetailDO> details = purchaseOrderDetailService.list(
	                new LambdaQueryWrapper<PurchaseOrderDetailDO>()
	                        .eq(PurchaseOrderDetailDO::getOrderId, ruku.getCgId())
	        );
	        ArrayList<HashMap> orderDetails = new ArrayList<>();
	        for (PurchaseOrderDetailDO detail : details) {
	            HashMap<String, Object> orderDetail = new HashMap<>();
	            ChanpingDO chanpingDO = chanpingService.get(detail.getProductId());
	            orderDetail.put("productId", detail.getProductId());
	            orderDetail.put("price", detail.getPrice());
	            orderDetail.put("num", detail.getNum());
	            orderDetail.put("productName", chanpingDO.getCpName());
	            orderDetail.put("detailId", detail.getId());
	            orderDetails.add(orderDetail);
	        }
	        model.addAttribute("purchaseOrder", map);
	        model.addAttribute("orderDetails", orderDetails);
		
		
		
		
		model.addAttribute("ruku", ruku);
	    return "system/ruku/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("system:ruku:add")
	public R save( RukuDO ruku){
		
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");//设置日期格式
		String name="RK"+df.format(new Date());
		ruku.setRkDabhao(name);
		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		ruku.setCreatId(ShiroUtils.getUser().getUserId().intValue());
		ruku.setCreatName(ShiroUtils.getUser().getUsername());
		ruku.setCreatTime(df2.format(new Date()));
		
		if(rukuService.save(ruku)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("system:ruku:edit")
	public R update( RukuDO ruku){
		ruku.setCheck(1);
		SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		ruku.setUpdateId(ShiroUtils.getUser().getUserId().intValue());
		ruku.setUpdateName(ShiroUtils.getUser().getUsername());
		ruku.setUpdateTime(df2.format(new Date()));
		rukuService.update(ruku);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("system:ruku:remove")
	public R remove( Integer id){
		if(rukuService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("system:ruku:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		rukuService.batchRemove(ids);
		return R.ok();
	}
	
	/**
	 * 审核
	 */
	@PostMapping( "/check")
	@ResponseBody
	@RequiresPermissions("system:ruku:check")
	public R check(@RequestParam("ids[]") Integer[] ids){
		 RukuDO ruku=new RukuDO();
		 for (Integer integer : ids) {
			 	ruku.setId(integer);
			 		ruku.setCheck(2);
				rukuService.update(ruku);
				RukuDO ruku2 = rukuService.get(ruku.getId());
				CkkucunDO kucun=new CkkucunDO();
				List<CkkucunDO> detailList=rukuService.getDaillist(ruku2.getCgId());
				for (CkkucunDO ckkucunDO : detailList) {
					kucun.setCpId(ckkucunDO.getCpId());
					kucun.setAllnumber(ckkucunDO.getAllnumber());
					ckkucunService.update(kucun);
				}
		}
		return R.ok();
	}
	/**
	 * 审核不通过
	 */
	@PostMapping( "/checkFalse")
	@ResponseBody
	@RequiresPermissions("system:ruku:check")
	public R checkFalse(@RequestParam("ids[]") Integer[] ids){
		 RukuDO ruku=new RukuDO();
		 for (Integer integer : ids) {
			 ruku.setId(integer);
			 ruku.setCheck(3);
				rukuService.update(ruku);
		}
		return R.ok();
	}

	@Log("导出")
	@GetMapping("/export")
	@RequiresPermissions("system:ruku:export")
	public void exportTemplate(HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {
		String fileName = "入库管理" + DateUtil.date().toString(DatePattern.PURE_DATETIME_PATTERN) + ".xls";
		List<RukuDO> productList =  rukuService.findLitsByParama(params);
		List<RukuExcelDTO> list = new ArrayList<>();
		productList.forEach(rukuDTO ->{
			RukuExcelDTO rukuExcelDTO = new RukuExcelDTO();
			BeanUtils.copyProperties(rukuDTO,rukuExcelDTO);
			if(Objects.nonNull(rukuDTO.getCheck())){
				//1待审核，2审核通过，3审核未通过
				if(1 == rukuDTO.getCheck()){
					rukuExcelDTO.setCheck("待审核");
				}else if(2 == rukuDTO.getCheck()){
					rukuExcelDTO.setCheck("审核通过");
				}else if(3 == rukuDTO.getCheck()){
					rukuExcelDTO.setCheck("审核未通过");
				}
			}else{
				rukuExcelDTO.setCheck("开立");
			}

			list.add(rukuExcelDTO);
		} );
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), RukuExcelDTO.class, list);
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
